import "../../../../scss/activity/group_buy/million_buy.scss";
import $ from "jquery";
import "../../../utils/weui";
import moment from "moment";
import ps from "../../../common/million_buy_variable";
import Vue from "vue";
import ReadSection from "../../components/readSection";
import FuncBanner from "../../components/funcbanner";
import CtrlPlay from "../../components/ctrlplay";
import UserJoin from "../../components/userJoin";
import SharePop from "../../components/sharePop";
import viewAddFooter from "../../components/viewAddFooter";
import com from "../../../utils/common";
import count from "../../../utils/countdown";
import wxtool from "../../components/weixin";
import setWxShare from "../../components/setWxShare";
import NoticePop from "../../components/noticeWay";
import Scroll from "../../../utils/rankSrcoll";

import wxpay from "../../components/wxpay";
let user = wxtool.getWxUserinfo();
console.log(user)
$(function () {
  let page = {
    _actid: com.getUrlParam("actid") ? com.getUrlParam("actid") : 1,
    _joinid: com.getUrlParam("joinid") ? com.getUrlParam("joinid") : 1,
    _ispreview: com.getUrlParam("preview") ? com.getUrlParam("preview") : 0,
    _appdata: {
      partinstatusall: ps, // 所有状态
      partinstatus: ps.NotJoin, //当前状态
      countDown: {
        days: "xx",
        hours: "xx",
        minutes: "xx",
        seconds: "xx"
      },
      successJoin: [],
      JoinerRank:[],
      Joiners: 0,
      MaxJoiners: 6,
      NowPrice: 500,
    },
    _app: {},
    _init: function () {
      // 获取活动数据
      let self = this;
      com.ajax({
        url: "/act/millionBuy/getActDetial",
        data: {
          Actid: self._actid,
          Joinid: self._joinid,
          Openid: user.openid,
        },
        ok: function (data) {
          let temp = data["msg"];
          console.log(data)
          if (temp !== "fail" && typeof temp === "object") {
            if (temp.Catgory == "group_buy/million_buy") {

              $("#PageTitle").html(temp.Title)

              temp.Actid = self._actid;
              temp.Prizes = JSON.parse(temp.Prizes);
              temp.StartDate = moment(temp.StartTime).format("YYYY-MM-DD HH:mm");
              temp.EndDate = moment(temp.EndTime).format("YYYY-MM-DD HH:mm");
              temp.Content = JSON.parse(temp.Content);
              temp.Other = JSON.parse(temp["Other"]);
              // 分享相关信息
              let ShareMsg = {};
              ShareMsg.ShareImg = temp.ShareImg;
              ShareMsg.ShareTitle = temp.ShareTitle ? temp.ShareTitle : temp.Title;
              ShareMsg.ShareContent = temp.ShareContent;
              self._appdata.ShareMsg = ShareMsg;

              // 判断状态
              self._appdata.partinstatus = self._checkActStatus(data);
              let ActStatus = {};
              ActStatus.partinstatusall = ps;
              ActStatus.partinstatus = self._appdata.partinstatus;
              self._appdata.ActStatus = ActStatus;

              if (self._joinid > 1) {
                let JoinerMsg = {};
                JoinerMsg.Name = data["extra"].Name;
                self._appdata.JoinerMsg = JoinerMsg;
              }


              // 得到参加人数
              self._appdata.Joiners = data["Joiners"];
              self._appdata.MaxJoiners = temp.Prizes.MaxPerson;
              // 得到现在价格
              self._appdata.NowPrice = self._checkPrizes(self._appdata.Joiners, temp.Prizes);

              $.extend(self._appdata, temp);
              console.log(self._appdata);
              console.log(temp);
              self._loadTemp()
            }else{
              com.alertDialog("类型错误")
            }
          } else {
            com.alertDialog("活动不存在")
          }
        }
      });

    },

    _checkPrizes: function (joiners, prize) {
      let ladderPrz = prize.LadderArr;
      if (joiners < ladderPrz[0].PeoNum) {
        return prize.MaxPrice;
      }
      for (let i = ladderPrz.length - 1; i >= 0; --i) {
        if (joiners >= ladderPrz[i].PeoNum) {
          return ladderPrz[i].Price;
        }
      }
    },
    // 根据状态判断数据传输,页面交互
    _analysisStatus: function () {
      let self = this;
      if (self._ispreview) {
        $(".preview-footer a:first-child").attr("href", "/dist/activity/group_buy/million_buy_edit.html?actid=" + self._actid)
        $(".preview-footer a:last-child").attr("href", "/dist/activity/group_buy/million_buy.html?actid=" + self._actid)
      }
      // 用户信息(当打开的是已经有用户报名的链接时)(当是用户打开时)
      if (self._joinid > 1) {
        // 检测是否帮忙已经帮忙(是否已经在伙伴里面)
        // 每次用户打开链接都填充分享内容
        let shareData = {
          ShareImg: self._appdata.ShareMsg.ShareImg,
          ShareContent: self._appdata.ShareMsg.ShareContent,
          Actid: self._actid,
        }
        let shareTitle = self._appdata.ShareMsg.ShareTitle;
        let joinerMsg = self._appdata.JoinerMsg;
        console.log(joinerMsg)
        shareData.ShareTitle = joinerMsg.Name + "正在参加" + shareTitle;
        setWxShare.SetShare(shareData)
      }
      else {

        if (!self._ispreview) {
          // 没有人报名时的情况(大概率商家页)
          // 当是商家保存完活动打开页面后
          let checkEditUser = com.getdb(self._actid);
          if (checkEditUser) {
            $(".share_mask").show();
            com.showCenter($(".share_pop"));
            com.savedb(self._actid, false)
          }
          console.log(checkEditUser);
          let shareData = {
            ShareTitle: self._appdata.ShareMsg.ShareTitle,
            ShareImg: self._appdata.ShareMsg.ShareImg,
            ShareContent: self._appdata.ShareMsg.ShareContent,
            Actid: self._actid,
          }
          setWxShare.SetShare(shareData)
        }
      }
      // 跳出报名成功弹窗(此时标识用户在自己页面)
      if (self._appdata.partinstatus == self._appdata.partinstatusall.JoinDone) {
        let saveKey = user.openid + self._actid;
        let pageActId = com.getdb(saveKey);
        // 当当前用户第一次打开页面时(此时没有存储活动id)
        if (pageActId != self._actid) {
          com.savedb(saveKey, self._actid);
          $('.notice_msg').show()
          com.showCenter($('.sign-suc'));
          // 点击页面自动刷新
          $("#app").on("click", ".sign-suc-footer,.mask", function () {
            $(".mask,.notice_msg,.sign-suc").hide();
          });
        }
      }
    },
    _checkActStatus: function (act) {
      let self = this;
      console.log(act)
      let temp = act['msg'];
      let start = moment(temp.StartTime);
      let end = moment(temp.EndTime);
      let now = moment();

      //判断活动是否开始
      if (now.isBefore(start)) {
        return ps.AtActInActiveStart
      }
      //判断活动是否开始
      if (now.isAfter(end)) {
        return ps.AtActInActiveEnd
      }
      if(act.Joiners == 0){
        return ps.NotJoin
      }
      //判断用户是否参与过活动(joinerid 与openid对上了)
      if (act.isPageJoin) {
        return ps.JoinDone
      }
      //判断当前打开页面的是不是用户
      if (act.Joiners > 0 && act.isJoiner) {
        return ps.ParterDone
      }

      return ps.JoinJustNow
    },
    _loadTemp: function () {
      let self = this;
      Vue.component("read-section", ReadSection)
      Vue.component("func-banner", FuncBanner);
      Vue.component("music", CtrlPlay);
      Vue.component("user-join", UserJoin);
      Vue.component("share-pop", SharePop);
      Vue.component("add-msg", viewAddFooter);
      Vue.component("notice-pop", NoticePop);
      self._app = new Vue({
        el: "#app",
        data: self._appdata,
        methods: {
          getReadSection: function (val) {
            console.log(val)
            this.Section = val["Section"];
          },
          AlertJoinPop: function () {
            let msg = '<p style="text-align:left;color:#333;">①报名前可先联系商家，确认活动真实性以及记录联系方式哦！<br/>②如发现虚假活动，请在客牛公众号回复我们。</p>';
            layer.open({
              content: msg
              , btn: ['确定', '取消'],
              yes: function () {
                layer.closeAll();
                $('.pop_mask').show();
                com.showCenter($(".pop_user_msg"))
              }
            });
          },
          SendFriend: function () {
            $(".notice_msg").show();
            com.showCenter($('.sign-suc'));
          },
          // 提交报名信息
          UserJoinAct: function (data) {
            let JoinData = {};
            JoinData.Actid = self._actid;
            JoinData.Joinid = self._joinid;
            JoinData.ActivityCat = "group_buy/million_buy";
            JoinData.Name = data["Name"];
            JoinData.Mobile = data["Mobile"];
            JoinData.Other = data["Other"];
            JoinData.Openid = user.openid;
            console.log(data);
            console.log(JoinData);
            com.ajax({
              url: "/act/millionBuy/joinMillionBuy",
              method: "post",
              data: JoinData,
              ok: function (data) {
                console.log(data);
                if (data["msg"] == "ok") {
                  let detail = data['joinin'];
                 self._payMoney(detail.Id)
                } else if (data["msg"] == "fail") {
                  com.alertDialog("同一活动不能重复报名")
                }
              }
            })
          },
          PayMoney:function(){
            let joinid = self._joinid;
            console.log("这是joinerid"+joinid)
            self._payMoney(joinid)
          },
          // 返回自己页面
          BackMine: function () {
            self._getJoinByOpenid(1)
          },
        },
        updated: function () {
          console.log("更新");
        },
      });
      self._analysisStatus();
      self._afterTemp();
    },
    _afterTemp: function () {
      let self = this;
      $("#app").on("click", ".mask,.cancel,.pop_mask", function () {
        $(".mask,.pop_mask").hide();
      })

      $("#app").on("click", ".share_pop,.pop_user_msg", function (event) {
        event.stopPropagation();
      })
      let main = {
        runningMan: function () {   // 接龙人数增加时进度变化
          if(self._app.Joiners >= self._app.MaxJoiners){
            self._app.Joiners = self._app.MaxJoiners;
            self._app.partinstatus = self._app.partinstatusall.AtActInActiveEnd;
          }
          $("#app").find(".schedule_status").css("width", (100 - self._app.Joiners / self._app.MaxJoiners * 100) + "%");

          $("#app").find(".running_man").css("left", (self._app.Joiners / self._app.MaxJoiners * 95) + "%");
        }
      };
      // 倒计时
      let countDownTime = setInterval(function () {
        let timeRecord = count.computedTime(moment(self._app.EndDate).format("X"));
        if (timeRecord) {
          self._app.countDown = timeRecord;
        } else {
          self._app.partinstatus = self._app.partinstatusall.AtActInActiveEnd;
          clearInterval(countDownTime)
        }
      }, 1000);

      if (self._app.successJoin.length) {
        let userEq = 0;
        setInterval(function () {
          if (userEq >= self._app.successJoin.length) {
            userEq = 0;
          }
          $(".cut_price_msg").text(self._app.successJoin[userEq]);
          userEq++;
        }, 2000);
      }
      main.runningMan();
      // 弹幕
      self._getJoinerTime()
      // 排行榜
      let obj = {
        url: "/act/millionBuy/getJoinTimeRank",
        data: {
          PageNum: 20,
          Actid: page._actid,
        },
        callback: self._analysisData
      }
      Scroll.StartScroll(obj)
    },
    _getJoinByOpenid: function (status) {
      let self = this;
      com.ajax({
        url: "/act/millionBuy/getJoinUserDetail",
        data: {
          Openid: user.openid,
          Actid: self._actid,
        },
        ok: function (dat) {
          console.log(dat);
          let joinMsg = dat["res"];
          console.log(joinMsg);
          if (joinMsg["Id"] > 0) {
            if (status) {
              window.location = "/dist/activity/group_buy/million_buy.html?actid=" + self._actid + "&joinid=" + joinMsg["Id"];
            }
          } else {
            com.alertDialog("您还未参加活动");
          }
        }
      })
    },

    // 付款,以及付款成功后效验
    _payMoney:function (joinid) {
      let self = this;
      com.ajax({
        url: "/wx/createOrder",
        data: {
          fee: 1,
          reqUrl: window.location.href,
          openid: user.openid,
          actid: self._actid,
          joinid: joinid,
        },
        ok: function (data) {
          //进入支付流程
          data.ok = function () {
            com.ajax({
              url:"/act/millionBuy/paySuccess",
              data:{
                Joinid:joinid,
              },
              ok:function (data) {
                console.log(data)
                if(data["res"] > 0){
                  self._getJoinByOpenid(1)
                }
              }
            })

          }
          data.fail = function () {
            console.log("删除" + joinid)
            com.ajax({
              url:"/act/deleteJoiner",
              data:{
                Openid: user.openid,
                Joinid: joinid,
              },
              ok:function (data) {
                console.log(data)
                if(data["res"] > 0){
                  com.alertDialog("您已取消支付");
                  $(".pop_mask").hide()
                }
              }
            })
          }
          wxpay(data)
        }
      });
    },
    _analysisData: function (data) {
      for (let i = 0; i < data.length; i++) {
        page._appdata.JoinerRank.push({
          "Name": data[i].Name,
          "JoinTime": moment(data[i].Time).format("YYYY-MM-DD HH:mm")
        })
      }
    },
    // 获取加入接龙用户信息
    _getJoinerTime: function () {
      let self = this;
      com.ajax({
        url: "/act/millionBuy/getJoinTime",
        data: {
          Actid: self._actid,
        },
        ok: function (data) {
          console.log(data);
          console.log(data["res"])
          let lasJoiners = data["res"];
          for (let i = 0; i < lasJoiners.length; i++) {
            self._app.successJoin.push(lasJoiners[i].Name + "在" + moment(lasJoiners[i].Time).format("YYYY-MM-DD HH:mm") + "参加接龙");
          }

          if (self._app.successJoin.length) {
            let userEq = 0;
            setTimeout(function () {
              if (userEq >= self._app.successJoin.length) {
                userEq = 0;
              }
              $(".cut_price_msg").text(self._app.successJoin[userEq]);
              userEq++;
            }, 0)
            setInterval(function () {
              if (userEq >= self._app.successJoin.length) {
                userEq = 0;
              }
              $(".cut_price_msg").text(self._app.successJoin[userEq]);
              userEq++;
            }, 2000);
          }else {
            $(".cut_price_msg").text("还没有人参加接龙");
          }
        }
      })

    }
  }
  page._init();
});
